package com.yunyike.controller.region;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.RequestConstant;
import com.yunyike.model.Region;
import com.yunyike.service.IRegionService;
import com.yunyike.utils.JsonUtils;

/**
 * @author zhengqiang.shi
 * 2015年12月22日 下午3:36:12
 */
@Controller
@RequestMapping(value=RequestConstant.REGION)
public class RegionController {

	@Autowired
	private IRegionService regionService;
	
	/**
	 * 获取所有省份
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.REGION_ALL_PRO)
	public String findProvince(HttpServletResponse response) throws IOException{
		
		List<Region> regions = regionService.findAllProvince();
		
		if(regions == null || regions.isEmpty()){
			return null;
		}
		String objectAsString = JsonUtils.ObjectAsString(regions);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(objectAsString);
		
		return null;
	}
	
	/**
	 * 根据省份获取城市列表
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.REGION_CITY_BY_PRO+"/{provinceId}")
	public String findCityByProvinceId(@PathVariable Integer provinceId,HttpServletResponse response) throws IOException{
		
		List<Region> regions = regionService.findCityByProvinceId(provinceId);
		
		
		if(regions == null || regions.isEmpty()){
			return null;
		}
		String objectAsString = JsonUtils.ObjectAsString(regions);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(objectAsString);
		
		return null;
	}
	
	/**
	 * 根据城市获取区域
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.REGION_AREA_BY_CITY+"/{cityId}")
	public String findAreaByCityId(@PathVariable Integer cityId,HttpServletResponse response) throws IOException{
		
		List<Region> regions = regionService.findAreaByCityId(cityId);
		
		if(regions == null || regions.isEmpty()){
			return null;
		}
		String objectAsString = JsonUtils.ObjectAsString(regions);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(objectAsString);
		
		return null;
	}
}
